import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AdminApiService } from './../api/admin-api.service';
import { Injectable } from '@angular/core';
import { sha256 } from 'js-sha256';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(
    private adminApi: AdminApiService,
    private message: NzMessageService,
    private router: Router,
  ) { }

  getToken(): string {
    return this.getCookie('token');
  }

  loggin(username: string, rawPassword: string): void {
    const password = sha256(rawPassword);
    this.adminApi.loggin(username, password).subscribe(
      token => {
        const bearerToken = 'Bearer ' + token;
        this.setCookie('token', bearerToken, 7);
        this.router.navigateByUrl('/overview');
      },
      err => {
        this.message.error('登陆错误');
      }
    );
  }

  logout(): void {
    this.deleteCookie('token');
    this.router.navigateByUrl('/login');
  }

  private getCookie(cname: string): string {
    const name = cname + '=';
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for (let caItem of ca) {
      while (caItem.charAt(0) === ' ') {
        caItem = caItem.substring(1);
      }
      if (caItem.indexOf(name) === 0) {
        return caItem.substring(name.length, caItem.length);
      }
    }
    return '';
  }

  private setCookie(cname: string, cvalue: string, exdays: number): void {
    const d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    const expires = 'expires=' + d.toUTCString();
    document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
  }

  private deleteCookie(cname: string): void {
    document.cookie = cname + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  }
}
